package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"time"

	"google.golang.org/grpc"

	pb "gitee.com/aoliang/graceful/graceful_update_grpc/proto"
)

const (
	address2 = "localhost:50051"
)

func main() {
	for i := 0; i < 10; i++ {
		time.Sleep(2 * time.Second)
		go func(i int) {

			conn, err := grpc.Dial(address2, grpc.WithInsecure())
			if err != nil {
				log.Fatalf("did not connect: %v", err)
			}
			defer conn.Close()

			c := pb.NewGreeterClient(conn)
			streamClient, err := c.SayStreamHello(context.Background())
			go func() {
				for {
					in, err := streamClient.Recv()
					if err == io.EOF {
						// read done.
						return
					}
					if err != nil {
						fmt.Printf("Failed to receive a message : %v", err)
						return
					}
					fmt.Printf("Got message %s\n", in.Message)
				}
			}()

			var count int
			for {
				name := fmt.Sprintf("message-%d-%d", i, count)
				if err := streamClient.Send(&pb.HelloRequest{Name: name}); err != nil {
					fmt.Printf("Failed to send a note: %v\n", err)
					break
				}
				count++
				time.Sleep(1 * time.Second)
			}
		}(i)
	}

	time.Sleep(100 * time.Second)
}
